std::placeholders

From Cppreference

Jump to: navigation, search
Defined in header <functional>

namespace placeholders {

    extern /*unspecified*/ _1;
    extern /*unspecified*/ _2;
    .
    .
    extern /*unspecified*/ _N;

}

The std::placeholders namespace contains the placeholder objects [_1, . . . _N] where N represents an implementation defined number for maximum replaceable function arguments.

[edit] Example

The following code shows the creation of function objects with a placeholder argument.

#include <functional>
#include <string>
#include <iostream>
 
void goodbye(const std::string& s)
{
    std::cout << "Goodbye " << s << '\n';
}
 
class Object {
public:
    void hello(const std::string& s)
    {
        std::cout << "Hello " << s << '\n';
    }
};
 
int main(int argc, char* argv[])
{
    typedef std::function<void(const std::string&)> ExampleFunction;
    Object instance;
    std::string str("World");
    ExampleFunction f = std::bind(&Object::Hello, &instance, 
                                  std::placeholders::_1);
 
    // equivalent to instance.hello(str)
    f(str);
    f = std::bind(&goodbye, std::placeholders::_1);
 
    // equivalent to goodbye(str)
    f(str);    
    return 0;
}

Output:

Hello World
Goodbye World
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
In other languages